package com.qsl.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author 青石路
 * @date 2021/4/11 21:05
 */
@RestController
@RequestMapping("redis")
@Slf4j
public class RedisController {

    @Resource
    private RedissonClient redissonClient;

    @RequestMapping("secKill")
    public String secKill(int pid, InetUtils inetUtils) {
        String ipAddress = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
        RLock lock = redissonClient.getLock("sec_kill_" + pid);
        try {
            log.info("线程：{}, 准备获取锁...", Thread.currentThread().getName());
            lock.lock();
            log.info("线程：{}, 获取到锁, 开始执行业务...", Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(5);
            log.info("线程：{}, 业务执行完成", Thread.currentThread().getName());
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            lock.unlock();
            log.info("线程：{}, 成功释放锁", Thread.currentThread().getName());
        }

        return "success";
    }

    @RequestMapping("random")
    public Object SecureRandom() {
        SecureRandom secureRandom = new SecureRandom();
        int nextInt = secureRandom.nextInt(1000);   // 产生 0 ~ 999 的随机整数

        if (nextInt <= 0) {
            return nextInt + " - 一等奖";
        }
        if (nextInt > 0 && nextInt <= 10) {
            return nextInt + " - 二等奖";
        }
        if (nextInt > 10 && nextInt <= 30) {
            return nextInt + " - 三等奖";
        }

        return nextInt + " - 谢谢参与";
    }
}
